<template>
  <section class="page-content">
    <el-tabs value="basic" @tab-click="handleClick" type="border-card">
      <el-tab-pane label="基本信息" name="basic">
        <el-form size="medium" :model="formData" :rules="rules" ref="formData" label-width="100px" class="form-goods-basic">
          <el-form-item label="课程名称" prop="name">
            <el-input v-model="formData.name"></el-input>
          </el-form-item>
          <el-form-item label="课程售价" prop="price" >
            <el-input v-model.number="formData.price"></el-input>
          </el-form-item>
          <el-form-item label="课程时长(分)" prop="length_of_time" >
            <el-input type="number" v-model.number="formData.length_of_time"></el-input>
          </el-form-item>
          <el-form-item label="赠送积分" prop="give_integral">
            <el-input type="number" v-model="formData.give_integral"></el-input>
          </el-form-item>
          <el-form-item label="兑换积分" prop="exchange_integral">
            <el-input type="number" v-model="formData.exchange_integral"></el-input>
          </el-form-item>
          <el-form-item label="课程排序" prop="order">
            <el-input type="number" v-model="formData.order"></el-input>
          </el-form-item>
          <el-form-item label="课程分类" prop="category_id">
            <el-select v-model.number="formData.category_id" placeholder="请选择所属分类">
              <el-option label="文化经典" :value="1"></el-option>
              <el-option label="能量禅修" :value="2"></el-option>
              <el-option label="易经风水" :value="3"></el-option>
              <el-option label="领袖商道" :value="4"></el-option>
              <el-option label="健康养生" :value="5"></el-option>
              <el-option label="积分课程" :value="6"></el-option>
              <el-option label="进阶高级" :value="7"></el-option>
              <el-option label="咨询老师" :value="8"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="一级提成" prop="bonus_ratio_1">
            <el-input v-model="formData.bonus_ratio_1"></el-input>
          </el-form-item>
          <el-form-item label="二级提成" prop="bonus_ratio_2">
            <el-input v-model="formData.bonus_ratio_2"></el-input>
          </el-form-item>
          <el-form-item label="授课老师" prop="user_id">
            <el-select v-model.number="formData.user_id" placeholder="请选择授课老师">
              <el-option v-for="(teacher, index) in teachers" :label="teacher.name" :key="index" :value="teacher.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="缩略图" prop="thumb">
            <el-upload
              class="thumb-uploader"
              accept="image/*"
              :action="$serverUrl + '/api/upload/thumbImage'"
              name="file"
              :data="{folder: 'course', width: 390, height: 300}"
              :show-file-list="false"
              :on-success="handleUploadSuccess"
              :before-upload="beforeUpload">
              <img v-if="formData.thumb" :src="$serverUrl + '/storage/' + formData.thumb" class="upload-thumb">
              <i v-else class="el-icon-plus thumb-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="是否上架" prop="is_on_sale">
            <el-switch v-model="formData.is_on_sale"></el-switch>
          </el-form-item>
          <el-form-item label="课程属性" v-if="isAdmin">
              <el-checkbox label="精品课程" name="is_best" v-model="formData.is_best"></el-checkbox>
              <el-checkbox label="必看课程" name="is_required" v-model="formData.is_required"></el-checkbox>
          </el-form-item>
          <el-form-item>
            <el-button :loading="loading" type="primary" @click="submitCourse('formData')">保存</el-button>
            <el-button @click="resetForm('formData')">重置</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="详细信息" name="body">
        <tinymce :height="500" v-model="formData.body"></tinymce>
        <el-form>
         <el-form-item class="form-goods-body">
            <el-button type="primary" :disabled="!isEdit" @click="submitGoodsContent()">保存</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>
  </section>
</template>

<script>
  import Tinymce from '@/components/tinymce/Editor'
  export default {
    name: 'course',
    data () {
      return {
        loading: false,
        visible: false,
        dialogImageUrl: '',
        dialogVisible: false,
        attachmentSize: 1,
        attachmentLimit: 5,
        attachmentWidth: 640,
        attachmentHeight: 425,
        teachers: [],
        tempData: {
          id: null,
          name: '',
          category_id: '',
          length_of_time: 100,
          user_id: '',
          thumb: '',
          price: '',
          give_integral: 0,
          exchange_integral: 0,
          order: 100,
          is_on_sale: false,
          is_best: false,
          is_required: false,
          body: '',
          bonus_ratio_1: 0.00,
          bonus_ratio_2: 0.00
        },
        formData: {},
        rules: {
          name: [
            { required: true, message: '请输入课程名称', trigger: 'blur' },
            { min: 1, max: 250, message: '长度在1到250个字符', trigger: 'blur' }
          ],
          category_id: [
            { required: true, type: 'number', message: '请选择课程分类', trigger: 'change' }
          ],
          user_id: [
            { required: true, type: 'number', message: '请选择老师', trigger: 'change' }
          ],
          thumb: [
            { required: true, message: '请上传缩略图', trigger: 'blur' }
          ],
          price: [
            { type: 'number', required: true, message: '该字段必填', trigger: 'blur' }
          ],
          order: [
            { required: true, message: '请填写排序', trigger: 'blur' }
          ],
          bonus_ratio_1: [
            { required: true, message: '该字段必填', trigger: 'blur' }
          ],
          bonus_ratio_2: [
            { required: true, message: '该字段必填', trigger: 'blur' }
          ]
        }
      }
    },
    components: { Tinymce },
    methods: {
      handleUploadSuccess (res, file) {
        this.formData.thumb = res
      },
      beforeUpload (file) {
        const isLt1M = file.size / 1024 / 1024 < 1
        if (!isLt1M) {
          this.$message.error('图片大小不能超过1MB!')
        }
        return isLt1M
      },
      handleClick (tab, event) {
        console.log(tab, event)
      },
      submitCourse (formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this._createOrEditCourse()
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      submitGoodsContent () {
        this.loading = true
        if (!this.isEdit) {
          this.$message.error('请先提交课程基本信息')
        }
        this.$http.put('/courses/' + this.formData.id, {body: this.formData.body})
        .then((response) => {
          this.loading = false
          this.$message.success('保存成功')
        }).catch((error) => {
          this.loading = false
          console.log(error)
        })
      },
      resetForm (formName) {
        this.$refs[formName].resetFields()
      },
      _createOrEditCourse () {
        this.loading = true
        this.$http({
          method: this.isEdit ? 'put' : 'post',
          url: this.isEdit ? '/courses/' + this.formData.id : '/courses',
          data: this.formData
        }).then((response) => {
          this.loading = false
          this.$message.success('保存成功')
          this.$router.push('/courses/' + response.data.id + '/edit')
        }).catch((error) => {
          this.loading = false
          console.log(error)
        })
      },
      _resetCourse () {
        this.formData = Object.assign({}, this.tempData)
      },
      _getData () {
        this.$http.get('/courses/' + this.$route.params.id + '/edit').then((response) => {
          this.formData = response.data
          this.$refs.goodsAttr.getAttrs(response.data.type_id, response.data.id)
        }).catch((error) => {
          console.log(error)
        })
      },
      _getTeachers () {
        this.$http.get('/users?role=Teacher&platform=backend&page_size=200').then((response) => {
          this.teachers = response.data.data
        }).catch((error) => {
          console.log(error)
        })
      }
    },
    computed: {
      isEdit () {
        return this.$route.meta.isEdit
      },
      thumb () {
        if (this.formData.thumb_img.indexOf('http:') === -1) {
          return this.$serverUrl + '/storage/' + this.formData.thumb_img
        }
        return this.formData.thumb_img
      },
      isAdmin () {
        let userInfo = this.$store.getters.userInfo
        if (!userInfo || !userInfo.roles) {
          return false
        }
        return userInfo.roles.some((item) => {
          return item === 'Admin'
        })
      }
    },
    watch: {
      '$route' (to, from) {
        if (!to.meta.isEdit) {
          this._resetCourse()
        } else {
          this._getData()
        }
      }
    },
    mounted () {
      this._resetCourse()
      this._getTeachers()
      if (this.isEdit) {
        this._getData()
      }
    }
  }
</script>
<style scoped lang="scss">
  .form-goods-basic {
    width: 700px;
    .el-select {
      width: 100%;
    }
  }
  .form-goods-body {
    margin-top: 20px;
  }
  .thumb-uploader, .thumb-uploader-icon, .thumb-img{
    width: 200px;
    height: 200px;
  }
  .thumb-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    overflow: hidden;
    &:hover {
      border-color: #20a0ff;
    }
    .thumb-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      line-height: 200px;
      text-align: center;
      &:hover {
        color: #20a0ff;
      }
    }
  }
  .dialog {
      .el-input {
        width: 100%;
      }
      .el-select {
        width: 100%;
      }
    } 
</style>